import org.jbox2d.collision.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.*;
import org.jbox2d.dynamics.contacts.*;
import org.jbox2d.dynamics.joints.*;
import org.jbox2d.p5.*;


int tileSize = 6;
int scaleFactor = 7;
int levelWidth = 16;
int levelHeight = 10;
Physics physics;

Ninja ninja;
Level currLevel;
ArrayList levels;

interface drawable {
  void draw();
}

class Ninja implements drawable {
  float x, y;
  PImage sprite;
  Ninja(float x, float y, PImage sprite) {
    this.x=x;
    this.y=y;
    this.sprite=sprite;
  }
  void draw() {
    image(sprite, x*tileSize, y*tileSize);
  }
}

class Level implements drawable {
  int w, h;
  char[][] tiles;
  Level(int w, int h, String[] tiles) {
    this.w=w;
    this.h=h;
    this.tiles= new char[h][w];
    loadLevel(tiles);
  }
  void loadLevel(String[] tiles) {
    for(int y = 0; y < h; y++)
      for(int x = 0; x < w; x++)
        this.tiles[y][x]=tiles[y].length()>x?tiles[y].charAt(x):' ';
  }
  void draw() {
    for(int y = 0; y < h; y++)
      for(int x = 0; x < w; x++)
        drawTile(x, y, tiles[y][x]);
  }
  void drawTile(int x, int y, char tile) {
    switch(tile) {
      case('#'):
      stroke(0);
      fill(200);
      rect(x*tileSize,y*tileSize,tileSize,tileSize);
      break;
      case('x'):
      noStroke();
      fill(#FF0000);
      rect(x*tileSize,y*tileSize,tileSize,tileSize);
      break;
      case(' '):
      break;
    }

  }
}

void setup() {
  size(tileSize*scaleFactor*levelWidth,tileSize*scaleFactor*levelHeight);
  
  ninja = new Ninja(0,4,loadImage("ninja.png"));
  currLevel = new Level(levelWidth,levelHeight,loadStrings("01.lvl"));
  levels = new ArrayList();
  levels.add(currLevel);

  InitPhysics();
  CreatePhysicsObjects();

}

void InitPhysics() {
  physics = new Physics(this, width, height);
  physics.setDensity(1.0);
}

void CreatePhysicsObjects() {
  // Middle of the world
  float hw = width / 2.0;
  float hh = height / 2.0;

  // A round object in the middle of the scene (center coordinates, radius)
  physics.createCircle(hw, hh, 50.0);
  // And two rectangles not far (coordinates of top-left, and bottom-right corners)
  physics.createRect(
	hw - 150, hh - 50,
	hw - 75, hh + 50
  );
  physics.createRect(
	hw + 75, hh - 40,
	hw + 175, hh + 40
  );
  // A polygon, defined by a list of vertices
  physics.createPolygon(
	hw + 150, hh - 100,
	hw, hh - 150,
	hw - 150, hh - 100
  );
} 

void draw() {
  background(255);

  pushMatrix();
  scale(scaleFactor);
  currLevel.draw();
  ninja.draw();
  popMatrix();
}
